import 'package:account_book/common/dao/history_dao.dart';
import 'package:account_book/common/entity/history.dart';
import 'package:account_book/pages/record/index.dart';
import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:get/get.dart';

class RecordController extends GetxController {


  final state = RecordState();

  @override
  void onReady() {
    super.onReady();
    _loadData();
  }

  void _loadData() async {
    DateTime now = state.currentDate;
    DateTime startDate = DateTime(now.year, now.month, 1);
    DateTime endDate = DateTime(now.year, now.month + 1, 0, 23, 59, 59);
    List<History> historyList = await HistoryDao.instance.queryListByDate(
        DateUtil.formatDate(startDate, format: "yyyy-MM-dd"), DateUtil.formatDate(endDate, format: "yyyy-MM-dd"));
    Map<String, HistoryDetail> dataMap = {};
    state.income = 0.0;
    state.expend = 0.0;
    state.surplus = 0.0;
    state.dealNum = historyList.length;
    if (historyList.isNotEmpty) {
      for (History history in historyList) {
        int type = history.type;
        DateTime createDate = DateTime.parse(history.createDate);
        String dayTime = DateUtil.formatDate(createDate, format: "yyyy-MM-dd");
        HistoryDetail? mapValue = dataMap[dayTime];
        mapValue ??= HistoryDetail();
        mapValue.date = DateUtil.formatDate(createDate, format: "MM月dd日");
        mapValue.week = DateUtil.getWeekday(createDate, languageCode: 'zh');
        if (type==1) {
          mapValue.expend = NumUtil.add(mapValue.expend, history.amount);
          state.expend = NumUtil.add(state.expend, history.amount);
        } else if (type==2) {
          mapValue.income = NumUtil.add(mapValue.income, history.amount);

          state.income = NumUtil.add(state.income, history.amount);
        }
        mapValue.detail.add(history);
        dataMap[dayTime] = mapValue;
      }
      state.surplus = NumUtil.subtract(state.income, state.expend);
    }
    state.listData.clear();
    for (String key in dataMap.keys) {
      state.listData.add(dataMap[key]!);
    }
  }

  void switchDate (DateTime dateTime) {
    state.currentDate = dateTime;
    _loadData();
  }

  void removeHistory(History history) {
    HistoryDao.instance.remove({"id": history.id});
    _loadData();
  }
}